package com.sidianzhong.sdz.controller;

import com.alibaba.fastjson.JSONObject;
import com.sidianzhong.sdz.annotation.BackLoginToken;
import com.sidianzhong.sdz.annotation.UserLoginToken;
import com.sidianzhong.sdz.model.BorrowMoney;
import com.sidianzhong.sdz.model.CoinInfo;
import com.sidianzhong.sdz.model.LoansAttestation;
import com.sidianzhong.sdz.model.UserWallet;
import com.sidianzhong.sdz.service.*;
import com.sidianzhong.sdz.utils.PageInfo;
import com.sidianzhong.sdz.utils.ResultModel;
import com.sidianzhong.sdz.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by hxg on 2016/10/06.
 */
@Api(description = "借款记录")
@Controller
public class BorrowMoneyController {

    @Autowired
    BorrowMoneyService borrowMoneyService;
    @Autowired
    CoinInfoService coinInfoService;
    @Autowired
    LoansAttestationService loansAttestationService;
    @Autowired
    UserWalletService userWalletService;

    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    @BackLoginToken
    @ApiOperation(value = "创建'借款记录'表中一条信息")
    @RequestMapping(value = "/borrowMoney/new", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object createBorrowMoney(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "borrowNum", required = false) String borrowNum,
            @RequestParam(value = "borrowAmount", required = false) Double borrowAmount,
            @RequestParam(value = "coinId", required = false) Integer coinId,
            @RequestParam(value = "periods", required = false) Integer periods,
            @RequestParam(value = "interest", required = false) Double interest,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "createTime", required = false) String createTime,
            @RequestParam(value = "lastUpdateTime", required = false) String lastUpdateTime
    ) {
        BorrowMoney item = new BorrowMoney();
        Date date = new Date();
        if (userId != null) {
            item.setUserId(userId);
        }
        if (borrowNum != null) {
            item.setBorrowNum(borrowNum);
        }
        if (borrowAmount != null) {
            item.setBorrowAmount(borrowAmount);
        }
        if (coinId != null) {
            item.setCoinId(coinId);
        }
        if (periods != null) {
            item.setPeriods(periods);
        }
        if (interest != null) {
            item.setInterest(interest);
        }
        if (status != null) {
            item.setStatus(status);
        }
        item.setCreateTime(new Date());
        item.setLastUpdateTime(new Date());
        BorrowMoney iteams = borrowMoneyService.create(item);
        boolean result = iteams != null;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @BackLoginToken
    @ApiOperation(value = "删除'借款记录'表中的某条记录")
    @RequestMapping(value = "/borrowMoney/delete", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object deleteBorrowMoney(
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "id") Integer id
    ) {
        BorrowMoney item = borrowMoneyService.get(id);
        if (null == item) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        int delete = borrowMoneyService.delete(id);
        boolean result = delete != 0;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @BackLoginToken
    @ApiOperation(value = "修改'借款记录'表中的某条记录")
    @RequestMapping(value = "/borrowMoney/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object editBorrowMoney(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "id") Integer id,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "borrowNum", required = false) String borrowNum,
            @RequestParam(value = "borrowAmount", required = false) Double borrowAmount,
            @RequestParam(value = "coinId", required = false) Integer coinId,
            @RequestParam(value = "periods", required = false) Integer periods,
            @RequestParam(value = "interest", required = false) Double interest,
            @RequestParam(value = "status", required = false) Integer status
    ) {
        BorrowMoney item = borrowMoneyService.get(id);
        if (null == item) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        if (userId != null) {
            item.setUserId(userId);
        }
        if (borrowNum != null) {
            item.setBorrowNum(borrowNum);
        }
        if (borrowAmount != null) {
            item.setBorrowAmount(borrowAmount);
        }
        if (coinId != null) {
            item.setCoinId(coinId);
        }
        if (periods != null) {
            item.setPeriods(periods);
        }
        if (interest != null) {
            item.setInterest(interest);
        }
        if (status != null) {
            item.setStatus(status);
        }
        item.setLastUpdateTime(new Date());
        int update = borrowMoneyService.update(item);
        boolean result = update != 0;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
    }

    @BackLoginToken
    @ApiOperation(value = "查询'借款记录'表中的某条记录")
    @RequestMapping(value = "/getBorrowMoneyById", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getBorrowMoneyById(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token") String token,
            @RequestParam(value = "id") Integer id
    ) {
        BorrowMoney item = borrowMoneyService.get(id);
        if (null == item) {
            return new ResponseEntity<>(ResultModel.error(), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResultModel.ok(item), HttpStatus.OK);
    }

    @BackLoginToken
    @ApiOperation(value = "查询'借款记录'表中的多条记录返回对象")
    @RequestMapping(value = "/borrowMoneys", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getBorrowMoneys(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token", required = false) String token,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "sortItem", required = false, defaultValue = "id") String sortItem,
            @RequestParam(value = "sortOrder", required = false, defaultValue = "desc") String sortOrder,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "borrowNum", required = false) String borrowNum,
            @RequestParam(value = "borrowAmount", required = false) Double borrowAmount,
            @RequestParam(value = "coinId", required = false) Integer coinId,
            @RequestParam(value = "periods", required = false) Integer periods,
            @RequestParam(value = "interest", required = false) Double interest,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "createTime", required = false) String createTime,
            @RequestParam(value = "lastUpdateTime", required = false) String lastUpdateTime
    ) {
        BorrowMoney item = new BorrowMoney();
        if (userId != null) {
            item.setUserId(userId);
        }
        if (borrowNum != null) {
            item.setBorrowNum(borrowNum);
        }
        if (borrowAmount != null) {
            item.setBorrowAmount(borrowAmount);
        }
        if (coinId != null) {
            item.setCoinId(coinId);
        }
        if (periods != null) {
            item.setPeriods(periods);
        }
        if (interest != null) {
            item.setInterest(interest);
        }
        if (status != null) {
            item.setStatus(status);
        }
        if (createTime != null) {
            item.setCreateTime(Tools.convertStringToDate(createTime, "yyyy-MM-dd HH:mm:ss"));
        }
        if (lastUpdateTime != null) {
            item.setLastUpdateTime(Tools.convertStringToDate(lastUpdateTime, "yyyy-MM-dd HH:mm:ss"));
        }
        PageInfo<BorrowMoney> list = borrowMoneyService.getListWithPaging(pageNum, pageSize, sortItem, sortOrder, item);
        return new ResponseEntity<>(ResultModel.ok(list), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "查询'借款记录'表中的多条记录返回自定义JSONObject")
    @RequestMapping(value = "/borrowMoneysObject", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getBorrowMoneysObject(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token", required = false) String token,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "sortItem", required = false, defaultValue = "id") String sortItem,
            @RequestParam(value = "sortOrder", required = false, defaultValue = "desc") String sortOrder,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "borrowNum", required = false) String borrowNum,
            @RequestParam(value = "borrowAmount", required = false) Double borrowAmount,
            @RequestParam(value = "coinId", required = false) Integer coinId,
            @RequestParam(value = "periods", required = false) Integer periods,
            @RequestParam(value = "interest", required = false) Double interest,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "createTime", required = false) String createTime,
            @RequestParam(value = "lastUpdateTime", required = false) String lastUpdateTime
    ) {
        BorrowMoney item = new BorrowMoney();
        if (userId != null) {
            item.setUserId(userId);
        }
        if (borrowNum != null) {
            item.setBorrowNum(borrowNum);
        }
        if (borrowAmount != null) {
            item.setBorrowAmount(borrowAmount);
        }
        if (coinId != null) {
            item.setCoinId(coinId);
        }
        if (periods != null) {
            item.setPeriods(periods);
        }
        if (interest != null) {
            item.setInterest(interest);
        }
        if (status != null) {
            item.setStatus(status);
        }
        if (createTime != null) {
            item.setCreateTime(Tools.convertStringToDate(createTime, "yyyy-MM-dd HH:mm:ss"));
        }
        if (lastUpdateTime != null) {
            item.setLastUpdateTime(Tools.convertStringToDate(lastUpdateTime, "yyyy-MM-dd HH:mm:ss"));
        }
        PageInfo<JSONObject> list = borrowMoneyService.getListWithObject(pageNum, pageSize, sortItem, sortOrder, item);
        List<JSONObject> list1 = list.getList();
        List<JSONObject> collect = list1.stream().map(ls -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", ls.getInteger("id"));
            jsonObject.put("userId", ls.getInteger("userId"));
            jsonObject.put("borrowNum", ls.getString("borrowNum"));
            jsonObject.put("borrowAmount", ls.getDouble("borrowAmount"));
            jsonObject.put("coinId", ls.getInteger("coinId"));
            jsonObject.put("periods", ls.getInteger("periods"));
            jsonObject.put("interest", ls.getDouble("interest"));
            jsonObject.put("status", ls.getInteger("status"));
            jsonObject.put("createTime", ls.getDate("createTime"));
            jsonObject.put("lastUpdateTime", ls.getDate("lastUpdateTime"));
            return jsonObject;
        }).collect(Collectors.toList());
        list.setList(collect);
        return new ResponseEntity<>(ResultModel.ok(list), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "借款")
    @RequestMapping(value = "/borrowMoney", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object borrowMoney(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token", required = false) String token,
            @RequestParam(value = "amount", required = false) Double amount,
            @RequestParam(value = "coinId", required = false) Integer coinId,
            @RequestParam(value = "periods", required = false) Integer periods
    ) {
        Integer user_id = (Integer) request.getAttribute("USER_ID");

        //第一步 首先查询 贷款资格
        BorrowMoney borrowMoney = new BorrowMoney();
        borrowMoney.setStatus(0);
        borrowMoney.setUserId(user_id);
        long count = borrowMoneyService.getCount(borrowMoney);
        if (count > 0) {
            return new ResponseEntity<>(ResultModel.error("已有贷款"), HttpStatus.OK);
        }

        //首先查询额度
        LoansAttestation loansAttestation = loansAttestationService.getByUser(user_id);
        if (loansAttestation == null) {
            return new ResponseEntity<>(ResultModel.error("没有贷款资格"), HttpStatus.OK);
        }
        if (loansAttestation.getLimits() < amount) {
            return new ResponseEntity<>(ResultModel.error("额度不够"), HttpStatus.OK);
        }

        Date date = new Date();

        //获取到利息
        double interest = 11.0;

        BorrowMoney item = new BorrowMoney();
        item.setUserId(user_id);
        item.setBorrowAmount(amount);
        item.setCoinId(coinId);
        item.setPeriods(periods);
        item.setStatus(0);
        item.setInterest(interest);
        item.setBorrowNum(String.valueOf(date.getTime()));
        item.setCreateTime(date);
        item.setLastUpdateTime(date);

        //转入钱包
        UserWallet userWallet = userWalletService.getByUserId(user_id, coinId);
        Double amount1 = userWallet.getAmount();
        userWallet.setAmount(amount1 + amount - interest);
        userWalletService.update(userWallet);

        return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
    }

    @UserLoginToken
    @ApiOperation(value = "借款记录")
    @RequestMapping(value = "/borrowMoneysRecord", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object borrowMoneysRecord(
            HttpServletRequest request,
            @RequestHeader(value = "X-Auth-Token", required = false) String token,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "sortItem", required = false, defaultValue = "id") String sortItem,
            @RequestParam(value = "sortOrder", required = false, defaultValue = "desc") String sortOrder
    ) {
        Integer user_id = (Integer) request.getAttribute("USER_ID");

        BorrowMoney item = new BorrowMoney();
        item.setUserId(user_id);

        PageInfo<JSONObject> list = borrowMoneyService.getListWithObject(pageNum, pageSize, sortItem, sortOrder, item);
        List<JSONObject> list1 = list.getList();
        List<JSONObject> collect = list1.stream().map(ls -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", ls.getInteger("id"));
            jsonObject.put("borrowNum", ls.getString("borrowNum"));
            jsonObject.put("borrowAmount", ls.getDouble("borrowAmount"));
            CoinInfo coinInfo = coinInfoService.get(ls.getInteger("coinId"));
            if (coinInfo == null) {
                jsonObject.put("coinName", "USDT");
            } else {
                jsonObject.put("coinName", coinInfo.getCoinSymbol());
            }
            jsonObject.put("periods", ls.getInteger("periods"));
            jsonObject.put("status", ls.getInteger("status"));
            jsonObject.put("createTime", ls.getDate("createTime"));
            jsonObject.put("lastUpdateTime", ls.getDate("lastUpdateTime"));
            return jsonObject;
        }).collect(Collectors.toList());
        list.setList(collect);
        return new ResponseEntity<>(ResultModel.ok(list), HttpStatus.OK);
    }
}
